package com.lagou.edu.mvcframework.filter;

import com.lagou.edu.mvcframework.util.SecurityUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LgSecurityFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //
        System.out.println("进入LgSecurityFilter");

        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String uri = httpServletRequest.getRequestURI();
        System.out.println("进入LgSecurityFilter");
        String user = httpServletRequest.getParameter("name");

        boolean isUserSecurity = SecurityUtil.isUserSecurity(uri, user);
        //如果没有权限
        if (!isUserSecurity) {
            HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
            httpServletResponse.sendError(404, String.format("用户%s没有权限", user));
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
